<?php


namespace App\Tool;


use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

class BaiduApi
{
    private $appId = '11479694';
    private $apiKey = 'W24u88qL31v6ZipBo8LGKkIB';
    private $secretKey  = '8qu3zPLxSW9GtXGdLByOGhN2kDzOilyt';
    private $accessToken = [];
    /**
     * idcard api url
     * @var string
     */
    private $idcardUrl = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard';

    /**
     * bankcard api url
     * @var string
     */
    private $bankcardUrl = 'https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard';

    /**
     * general api url
     * @var string
     */
    private $generalUrl = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general';

    /**
     * 获取access token url
     * @var string
     */
    private $accessTokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';

    private $httpClient = null;

    public function __construct($appId, $apiKey, $secretKey)
    {
        $this->appId = trim($appId);
        $this->apiKey = trim($apiKey);
        $this->secretKey = trim($secretKey);
        $this->accessToken = '';
        $this->httpClient = new Client(['verify'=>false]);
    }

    public function generateAccessToken()
    {
        $this->accessToken = Cache::get('baidu_accessToken');
        if ($this->accessToken){
            if(is_array($this->accessToken) && $this->accessToken['time'] + $this->accessToken['expires_in'] - 30 > time()){
                return $this->accessToken['access_token'];
            }
        }
        $response = $this->httpClient->post($this->accessTokenUrl, [
            'query' => [
                'grant_type' => 'client_credentials',
                'client_id' => $this->apiKey,
                'client_secret' => $this->secretKey
            ]
        ]);
        $this->accessToken = json_decode($response->getBody()->getContents(), true);
        $this->accessToken['time'] = time();
        Cache::put('baidu_accessToken', $this->accessToken, $this->accessToken['expires_in']);
        return $this->accessToken['access_token'];
    }

    public function idcardApi($image, $isFront)
    {
        $data = [
            'image' => base64_encode($image),
            'id_card_side' => $isFront ? 'front' : 'back',
            'detect_direction' => true,
        ];
        $response = $this->httpClient->post($this->idcardUrl, [
            'query' => [
                'access_token' => $this->generateAccessToken()
            ],
            'form_params' => $data
        ]);
        return json_decode($response->getBody()->getContents());
    }
}